package com.aiju.cash.ui.main;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.aiju.base.activity.BaseTitleActivity;
import com.aiju.bean.BlotterInfo;
import com.aiju.cash.R;
import com.aiju.cash.core.api.DataJson;
import com.aiju.cash.core.api.RefundApi;
import com.aiju.cash.ui.main.entity.Refund;
import com.aiju.common.PixValue;
import com.aiju.utils.PriceUtil;
import com.aiju.utils.T;
import com.aiju.utils.tts.BaiduTTSManager;
import com.aiju.widgit.dialog.MemberDialog;
import com.aiju.widgit.dialog.SimpleDialog;
import com.aiju.widgit.layout.LeftRightTextView;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.List;

import okhttp3.Call;

/**
 * @author: 佐为
 * @date: 2017-02-16 10:55
 * @version: V1.0
 * @Description: 退款
 */
public class RefundActivity extends BaseTitleActivity {

    //订单详情
    private LeftRightTextView money, type, time, running, info;

    //退款设置（在线退款，现金）
    private TextView online, cash;

    //退款原因
    private TextView client, quality, other;

    //原因 方式
    private String cause = "", remark = "";

    private BlotterInfo blotterInfo;

    private ListView mOrderListView;

    private EditText refundPriceEditText;

    //输入金额
    private String refundPrice;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_refund);
        setCenterTitle("退款");
        blotterInfo = (BlotterInfo) getIntent().getSerializableExtra("info");

        money = (LeftRightTextView) findViewById(R.id.refund_money);
        type = (LeftRightTextView) findViewById(R.id.refund_type);
        time = (LeftRightTextView) findViewById(R.id.refund_time);
        running = (LeftRightTextView) findViewById(R.id.refund_running);
        info = (LeftRightTextView) findViewById(R.id.refund_info);

        online = (TextView) findViewById(R.id.tv_refund_online);
        cash = (TextView) findViewById(R.id.tv_refund_cash);
        if (blotterInfo.getReceTypeDesc().equals("现金")) {
            remark = "现金退款";
            cash.setSelected(true);
            online.setVisibility(View.GONE);
        } else {
            String name = null;
            if (blotterInfo.getReceTypeDesc().contains("支付宝")) {
                name = "支付宝";
            } else if (blotterInfo.getReceTypeDesc().contains("微信")) {
                name = "微信";
            }
            online.setText(name + "原路退款");
            online.setSelected(true);
            remark = online.getText().toString();
        }

        client = (TextView) findViewById(R.id.tv_refund_client);
        quality = (TextView) findViewById(R.id.tv_refund_quality);
        other = (TextView) findViewById(R.id.tv_refund_other);

        refundPriceEditText = (EditText) findViewById(R.id.ev_refund);
        refundPriceEditText.setHint("最多可退" + PriceUtil.formatDouble(blotterInfo.getCanRefundFee()) + "元");
        mOrderListView = (ListView) findViewById(R.id.lv_order);
        refundPriceEditText.setFilters(new InputFilter[]{new InputFilter() {
                    @Override
                    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                        Double aDouble = Double.valueOf(dest + source.toString());
                        Double bDouble = Double.valueOf(blotterInfo.getCanRefundFee());
                        if (aDouble > bDouble) {
                            //T.ToastShort("退款金额必须小于收款金额");
                            return "";
                        } else {
                            if (dest.toString().contains(".")) {
                                int index = dest.toString().indexOf(".");
                                int mlength = dest.toString().substring(index).length();
                                if (mlength == 3) {
                                    //T.ToastShort("请输入两位小数");
                                    return "";
                                }
                            }
                            return source;
                        }

                    }
                }
                }
        );

        money.setContentText("￥" + PriceUtil.formatDouble(blotterInfo.getPrice()) + "  (" + blotterInfo.getTradeStatus() + ")");
        type.setContentText(blotterInfo.getReceTypeDesc());
        time.setContentText(blotterInfo.getCreateDate());
        running.setContentText(blotterInfo.getSerialNum());
        mOrderListView.setAdapter(new MyBaseAdapter(RefundActivity.this, blotterInfo.getDetails()));

        Drawable nav_up = getResources().getDrawable(R.mipmap.icon_blotter_down);
        nav_up.setBounds(0, 0, nav_up.getMinimumWidth(), nav_up.getMinimumHeight());
        info.getContentTextView().setCompoundDrawables(null, null, nav_up, null);
        info.getContentTextView().setCompoundDrawablePadding(PixValue.dp.valueOf(10));
        info.setContentText("" + blotterInfo.getDetails().size());
        info.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (findViewById(R.id.ly_blotter_detail).getVisibility() == View.GONE) {
                    findViewById(R.id.ly_blotter_detail).setVisibility(View.VISIBLE);
                    Drawable drawable = getResources().getDrawable(R.mipmap.icon_blotter_info);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                    info.getContentTextView().setCompoundDrawables(null, null, drawable, null);
                } else {
                    findViewById(R.id.ly_blotter_detail).setVisibility(View.GONE);
                    Drawable drawable = getResources().getDrawable(R.mipmap.icon_blotter_down);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                    info.getContentTextView().setCompoundDrawables(null, null, drawable, null);
                }
            }
        });

        selectType();
        selectCause();

        findViewById(R.id.btn_refund).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(remark)) {
                    T.ToastShort("请选择退款方式");
                    return;
                }
                if (remark.equals("现金退款")) {
                    showCashDialog();
                } else {
                    showOnlineDialog();
                }
            }
        });
    }

    /**
     * 检查输入金额
     *
     * @return
     */
    private boolean checkRefundPrice() {
        refundPrice = refundPriceEditText.getText().toString();
        if (TextUtils.isEmpty(refundPrice)) {
            T.ToastShort("请输入退款金额");
            return false;
        }

        Double aDouble = Double.valueOf(refundPrice);
        Double bDouble = Double.valueOf(blotterInfo.getPrice());
        if (aDouble > bDouble) {
            T.ToastShort("退款金额不能大于商品金额");
            return false;
        }
        if (aDouble == bDouble) {
            refundType = "all";
        } else {
            refundType = "part";
        }

        return true;
    }

    /**
     * 现金退款提示
     */
    private void showCashDialog() {
        if (!checkRefundPrice()) {
            return;
        }
        new SimpleDialog(this)
                .setLayoutParams()
                .setTitileText("请确认您的" + PriceUtil.formatDouble(refundPrice) + "元以现金的方式退还给顾客")
                .setOnSimpleClick(new SimpleDialog.OnSimpleClick() {
                    @Override
                    public void onCancel() {
                    }

                    @Override
                    public void onSubmit() {
                        cashRefund();
                    }
                }).show();

    }

    private String refundType = "";//退款类型 all：全部 part：部分
    private String outRefundNo = "";// 	退款单号，如果第一次退款失败会返回该值，重试退款需要传入该参数

    private void zfbpayRefund() {
        mDialogHelper.showLoadingProgressDialog();
        new RefundApi().zfbpayRefund(mUser.getStoreId(),
                blotterInfo.getSerialNum(),
                refundType,
                blotterInfo.getPrice(),
                refundPrice, mUser.getOperatorId(),
                mUser.getUserName(),
                cause, outRefundNo, new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        mDialogHelper.dismissProgressDialog();
                        T.ToastNetError();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        mDialogHelper.dismissProgressDialog();
                        DataJson dataJson = new DataJson(response);
                        if (dataJson.isPaySuccess()) {
                            goRefundView(true);
                        } else {
                            goRefundView(false);
                        }
                    }
                }
        );
    }

    private void wxpayRefund() {
        mDialogHelper.showLoadingProgressDialog();
        new RefundApi().wxpayRefund(mUser.getStoreId(),
                blotterInfo.getSerialNum(),
                refundType,
                blotterInfo.getPrice(),
                refundPrice, mUser.getOperatorId(),
                mUser.getUserName(),
                cause, outRefundNo, new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        mDialogHelper.dismissProgressDialog();
                        T.ToastNetError();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        mDialogHelper.dismissProgressDialog();
                        DataJson dataJson = new DataJson(response);
                        if (dataJson.isPaySuccess()) {
                            goRefundView(true);
                        } else {
                            goRefundView(false);
                        }
                    }
                }
        );
    }

    private void cashRefund() {
        mDialogHelper.showLoadingProgressDialog();
        new RefundApi().cashRefund(mUser.getStoreId(),
                blotterInfo.getSerialNum(),
                refundType,
                blotterInfo.getPrice(),
                refundPrice, mUser.getOperatorId(),
                mUser.getUserName(),
                cause, outRefundNo, new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        mDialogHelper.dismissProgressDialog();
                        T.ToastNetError();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        mDialogHelper.dismissProgressDialog();
                        DataJson dataJson = new DataJson(response);
                        if (dataJson.isPaySuccess()) {
                            goRefundView(true);
                        } else {
                            goRefundView(false);
                        }
                    }
                }
        );
    }


    /**
     * 线上退款提示
     */
    private void showOnlineDialog() {
        if (!checkRefundPrice()) {
            return;
        }
        new MemberDialog(this)
                .setLayoutParams()
                .setTitileText("请核对您的退款信息")
                .setMsgText("退款金额：" + PriceUtil.formatDouble(refundPrice) + "元"
                        + "\n退款方式：" + remark +
                        "\n退款操作不可取消，请核对无误后点击确认")
                .setOnSimpleClick(new MemberDialog.OnSimpleClick() {
                    @Override
                    public void onCancel() {
                    }

                    @Override
                    public void onSubmit() {
                        if (blotterInfo.getReceTypeDesc().contains("支付宝")) {
                            zfbpayRefund();
                        } else if (blotterInfo.getReceTypeDesc().contains("微信")) {
                            wxpayRefund();
                        }
                    }
                }).show();
    }

    /**
     * 跳转成功界面
     */
    private void goRefundView(boolean success) {
        String paytype = "";
        if (blotterInfo.getReceTypeDesc().contains("支付宝")) {
            paytype = "支付宝成功退款";
        } else if (blotterInfo.getReceTypeDesc().contains("微信")) {
            paytype = "微信成功退款";
        }

        if(!remark.equals("现金退款")){
            BaiduTTSManager.getInstance().speak(paytype + refundPrice + "元");
        }

        Intent intent = new Intent(RefundActivity.this, RefundSuccessActivity.class);
        intent.putExtra("price", refundPrice);
        intent.putExtra("type", blotterInfo.getReceTypeDesc());
        intent.putExtra("success", success);
        if (!success) {
            Refund refund = new Refund();
            refund.type = blotterInfo.getReceTypeDesc();
            refund.serialNum = blotterInfo.getSerialNum();
            refund.refundType = refundType;
            refund.price = blotterInfo.getPrice();
            refund.refundPrice = refundPrice;
            refund.cause = cause;
            intent.putExtra("refund", refund);
        }
        startActivity(intent);
    }

    /**
     * 退款方式的单选设置
     */
    private void selectType() {
        online.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                v.setSelected(true);
                cash.setSelected(false);
                remark = online.getText().toString();
            }
        });
        cash.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                v.setSelected(true);
                online.setSelected(false);
                remark = cash.getText().toString();
            }
        });
    }

    /**
     * 退款理由单选设置
     */
    private void selectCause() {
        client.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                v.setSelected(!v.isSelected());
                quality.setSelected(false);
                other.setSelected(false);
                cause = client.getText().toString();
            }
        });
        quality.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                v.setSelected(!v.isSelected());
                client.setSelected(false);
                other.setSelected(false);
                cause = quality.getText().toString();
            }
        });
        other.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                v.setSelected(!v.isSelected());
                quality.setSelected(false);
                client.setSelected(false);
                cause = other.getText().toString();
            }
        });
    }

    /**
     * 商品详情
     */
    private final class MyBaseAdapter extends BaseAdapter {

        private Context context;
        private List<BlotterInfo.Details> clerks;

        public MyBaseAdapter(Context context, List<BlotterInfo.Details> clerks) {
            this.context = context;
            this.clerks = clerks;
        }

        @Override
        public int getCount() {
            return clerks.size();
        }

        @Override
        public Object getItem(int position) {
            return clerks.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View rootView = LayoutInflater.from(context).inflate(R.layout.item_order, parent, false);

            TextView price = (TextView) rootView.findViewById(R.id.tv_order_price);
            TextView num = (TextView) rootView.findViewById(R.id.tv_order_num);
            TextView code = (TextView) rootView.findViewById(R.id.tv_order_code);
            TextView name = (TextView) rootView.findViewById(R.id.tv_order_name);

            BlotterInfo.Details good = clerks.get(position);
            price.setText(good.getPrice());
            num.setText("x" + good.getNum());
            code.setText(good.getCode());
            name.setText(good.getGoodsName());
            return rootView;
        }
    }
}
